package com.open.capacity.form.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.open.capacity.commons.PageResult;
import com.open.capacity.finance.util.uuid.UUIDUtils;
import com.open.capacity.form.dao.FormSchemeDao;
import com.open.capacity.form.dao.FormSchemeinfoDao;
import com.open.capacity.form.model.FormScheme;
import com.open.capacity.form.model.FormSchemeinfo;
import com.open.capacity.form.model.scheme.*;
import com.open.capacity.form.service.CustomerFormExtService;
import com.open.capacity.form.service.FormDbTableService;
import com.open.capacity.form.vo.FormDbTableFieldVo;
import com.open.capacity.vo.TreeExtVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class CustomerFormExtServiceImpl implements CustomerFormExtService {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private FormSchemeinfoDao schemeinfoDao;

    @Autowired
    private FormSchemeDao schemeDao;


    @Autowired
    private FormDbTableService tableService;


    @Override
    public PageResult<Map<String, Object>> getFormPageList(String schemeInfoId, Integer page, Integer limit, Map<String, Object> params) {
        FormSchemeinfo schemeinfo = schemeinfoDao.findById(schemeInfoId);
        FormScheme scheme = schemeDao.findById(schemeinfo.getSchemeId());
        FormSchemeModel formSchemeModel = null;
        try {
            formSchemeModel = objectMapper.readValue(scheme.getScheme(), FormSchemeModel.class);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("page", page);
        queryParams.put("limit", limit);
        for (Map.Entry<String, Object> item : params.entrySet()) {
            queryParams.put(item.getKey(), item.getValue());
        }

        String querySql = getQuerySql(formSchemeModel, params);
        return tableService.pageData(formSchemeModel.getDbId(), querySql, queryParams);
    }

    @Override
    public List<Map<String, Object>> getFormList(String schemeInfoId, Map<String, Object> params) {
        FormSchemeinfo schemeinfo = schemeinfoDao.findById(schemeInfoId);
        FormScheme scheme = schemeDao.findById(schemeinfo.getSchemeId());
        FormSchemeModel formSchemeModel = null;
        try {
            formSchemeModel = objectMapper.readValue(scheme.getScheme(), FormSchemeModel.class);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        String querySql = getQuerySql(formSchemeModel, params);
        return tableService.findData(formSchemeModel.getDbId(), querySql, params);
    }

    @Override
    public Map<String, List<Map<String, Object>>> getInstanceForm(String id, String keyValue) {
        Map<String, List<Map<String, Object>>> dataMap = new HashMap<>();
        FormSchemeinfo schemeinfo = schemeinfoDao.findById(id);
        FormScheme scheme = schemeDao.findById(schemeinfo.getSchemeId());
        FormSchemeModel formSchemeModel = null;
        try {
            formSchemeModel = objectMapper.readValue(scheme.getScheme(), FormSchemeModel.class);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        // 从表
        List<TreeExtVo<FormTableModel>> TableTree = new ArrayList<>();
        for (FormTableModel table : formSchemeModel.getDbTable()) {
            TreeExtVo<FormTableModel> treeone = new TreeExtVo<>();
            treeone.setData(table);
            treeone.setId(table.getName());
            treeone.setParentId(table.getRelationName());
            if (StringUtils.isEmpty(table.getRelationName())) {
                treeone.setParentId("0");
            }
            TableTree.add(treeone);
        }
        TableTree = new TreeExtVo<FormTableModel>().toTree(TableTree);

        // 确定表与组件之间的关系
        Map<String, List<FormCompontModel>> tableCompontsMap = new HashMap<>();
        for (FormTabModel tab : formSchemeModel.getData()) {
            for (FormCompontModel compont : tab.getComponts()) {
                if (StringUtils.isNotEmpty(compont.getTable())) {
                    if (!tableCompontsMap.containsKey(compont.getTable())) {
                        tableCompontsMap.put(compont.getTable(), new ArrayList<>());
                    }
                    if (compont.getType().equals("girdtable")) {
                        for (GridFieldModel item : compont.getFieldsData()) {
                            if (StringUtils.isNotEmpty(item.getField())) {
                                FormCompontModel _compont = new FormCompontModel();
                                _compont.setField(item.getField());
                                _compont.setId(item.getField());
                                if (!item.getType().equals("guid")) {
                                    _compont.setTable("girdfiled");
                                    tableCompontsMap.get(compont.getTable()).add(_compont);
                                }
                            }
                        }
                    } else {
                        tableCompontsMap.get(compont.getTable()).add(compont);
                    }
                }
            }
        }
        getInstanceTableData(TableTree, tableCompontsMap, formSchemeModel.getDbId(), keyValue, null, dataMap);
        return dataMap;
    }


    @Override
    public void saveInstanceForm(String id, String processId, String keyValue, Map<String, Object> formDataMap) {
        FormSchemeinfo schemeinfo = schemeinfoDao.findById(id);
        FormScheme scheme = schemeDao.findById(schemeinfo.getSchemeId());
        FormSchemeModel formSchemeModel = null;
        try {
            formSchemeModel = objectMapper.readValue(scheme.getScheme(), FormSchemeModel.class);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

        // 主从表分类
        List<FormTableModel> cTableList = new ArrayList<>();
        for (FormTableModel table : formSchemeModel.getDbTable()) {
            if (StringUtils.isEmpty(table.getRelationName())) {
                formSchemeModel.setMainTableName(table.getName());
                formSchemeModel.setMainTablePkey(table.getField());
            } else {
                cTableList.add(table);
            }
        }
        //表单组件按表进行分类
        List<String> ruleCodes = new ArrayList<>();
        String processIdFiled = "";
        Map<String, List<FormCompontModel>> tableMap = new HashMap<>();
        Map<String, FormCompontModel> girdTableMap = new HashMap<>();
        for (FormTabModel tab : formSchemeModel.getData()) {
            for (FormCompontModel compont : tab.getComponts()) {
                if (compont.getId().equals(processId)) {
                    processIdFiled = compont.getField();
                }
                if (StringUtils.isNotEmpty(compont.getTable())) {
                    if (!tableMap.containsKey(compont.getTable())) {
                        tableMap.put(compont.getTable(), new ArrayList<>());
                    }
                    if (compont.getType().equals("girdtable")) {
                        girdTableMap.put(compont.getTable(), compont);
                        for (GridFieldModel item : compont.getFieldsData()) {
                            FormCompontModel _compont = new FormCompontModel();
                            _compont.setField(item.getField());
                            _compont.setId(item.getField());
                            if (item.getType().equals("guid")) {
                                _compont.setType("girdguid");
                            }
                            tableMap.get(compont.getTable()).add(_compont);
                        }
                    } else {
                        if (compont.getType().equals("encode")) {
                            ruleCodes.add(compont.getRulecode());
                        }
                        tableMap.get(compont.getTable()).add(compont);
                    }
                }
            }
        }


        //数据保存或者更新
        if (StringUtils.isEmpty(keyValue)) {
            insertSql(formSchemeModel.getDbId(), formSchemeModel.getMainTableName(), formSchemeModel.getMainTablePkey(), processId, tableMap, formDataMap);
            for (FormTableModel table : cTableList) {
                String _value = "";
                String _filed = "";
                for (FormCompontModel compont : tableMap.get(table.getRelationName())) {
                    if (compont.getField().equals(table.getRelationField())) {
                        FormCompontModel newcompont = new FormCompontModel();
                        if (girdTableMap.containsKey(table.getName())) {
                            newcompont.setId(table.getField());
                        } else {
                            newcompont.setId(compont.getId());
                        }
                        newcompont.setField(table.getField());
                        _filed = table.getField();
                        _value = formDataMap.get(compont.getId()).toString();
                        tableMap.get(table.getName()).add(newcompont);
                        break;
                    }
                }
                if (girdTableMap.containsKey(table.getName())) {
                    // 编辑表格
                    try {
                        List<Map<String, Object>> girdDataJson = objectMapper.readValue(formDataMap.get(girdTableMap.get(table.getName()).getId()).toString(), List.class);
                        for (Map<String, Object> girdData : girdDataJson) {
                            girdData.put(_filed, _value);
                            insertSql(formSchemeModel.getDbId(), table.getName(), table.getField(), processId, tableMap, girdData);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        log.error(e.getMessage());
                    }

                } else {
                    insertSql(formSchemeModel.getDbId(), table.getName(), formSchemeModel.getMainTablePkey(), processId, tableMap, formDataMap);
                }
            }
        } else {
            // 更新主表数据
            String mainTablePkey = formSchemeModel.getMainTablePkey();
            if (StringUtils.isNotEmpty(processIdFiled)) {
                mainTablePkey = processIdFiled;
            }
            updateSql(formSchemeModel.getDbId(), formSchemeModel.getMainTableName(), mainTablePkey, keyValue, tableMap, formDataMap);
            for (FormTableModel table : cTableList) {
                if (girdTableMap.containsKey(table.getName())) {
                    String _value = "";
                    String _filed = "";
                    for (FormCompontModel compont : tableMap.get(table.getRelationName())) {
                        if (compont.getField().equals(table.getRelationField())) {
                            FormCompontModel newcompont = new FormCompontModel();
                            newcompont.setId(table.getField());
                            newcompont.setField(table.getField());
                            _filed = table.getField();
                            _value = formDataMap.get(compont.getId()).toString();
                            tableMap.get(table.getName()).add(newcompont);

                            String strSql = " DELETE FROM " + table.getName() + " WHERE " + table.getField() + " = '" + formDataMap.get(compont.getId()).toString() + "' ";
                            tableService.excuteSql(formSchemeModel.getDbId(), strSql, "");
                            break;
                        }
                    }

                    //编辑表格
                    try {
                        List<Map<String, Object>> girdDataJson = objectMapper.readValue(formDataMap.get(girdTableMap.get(table.getName()).getId()).toString(), List.class);
                        for (Map<String, Object> girdData : girdDataJson) {
                            girdData.put(_filed, _value);
                            insertSql(formSchemeModel.getDbId(), table.getName(), table.getField(), processId, tableMap, girdData);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        log.error(e.getMessage());
                    }
                } else {
                    for (FormCompontModel compont : tableMap.get(table.getRelationName())) {
                        if (compont.getField().equals(table.getRelationField())) {
                            updateSql(formSchemeModel.getDbId(), table.getName(), table.getField(), formDataMap.get(compont.getId()).toString(), tableMap, formDataMap);
                        }
                    }
                }
            }
        }

    }

    @Override
    public void deleteInstanceForm(String id, String keyValue) {
        FormScheme scheme = schemeDao.findById(id);
        FormSchemeModel formSchemeModel = null;
        try {
            formSchemeModel = objectMapper.readValue(scheme.getScheme(), FormSchemeModel.class);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

        // 确定主从表之间的关系
        List<TreeExtVo<FormTableModel>> TableTree = new ArrayList<>();
        for (FormTableModel table : formSchemeModel.getDbTable()) {
            TreeExtVo<FormTableModel> treeone = new TreeExtVo<FormTableModel>();
            treeone.setData(table);
            treeone.setId(table.getName());
            treeone.setParentId(table.getRelationName());
            if (StringUtils.isEmpty(table.getRelationName())) {
                treeone.setParentId("0");
            }
            TableTree.add(treeone);
        }
        TableTree = new TreeExtVo<FormTableModel>().toTree(TableTree);

        // 确定表与组件之间的关系
        Map<String, List<FormCompontModel>> tableComponts = new HashMap<>();
        for (FormTabModel tab : formSchemeModel.getData()) {
            for (FormCompontModel compont : tab.getComponts()) {
                if (StringUtils.isNotEmpty(compont.getTable())) {
                    if (!tableComponts.containsKey(compont.getTable())) {
                        tableComponts.put(compont.getTable(), new ArrayList<>());
                    }
                    tableComponts.get(compont.getTable()).add(compont);
                }
            }
        }
        deleteInstanceTable(TableTree, tableComponts, formSchemeModel.getDbId(), keyValue, null);
    }


    /**
     * 获取查询sql语句
     *
     * @param formSchemeModel 表单模板设置信息
     * @param queryParam
     * @return
     */
    private String getQuerySql(FormSchemeModel formSchemeModel, Map<String, Object> queryParam) {
        String querySql = "";
        String fieldSql = "";
        Map<String, String> girdTable = new HashMap<>();// 表格绑定的表
        Map<String, FormCompontModel> compontMap = new HashMap<>();
        Map<String, String> tableMap = new HashMap<>();

        int _index = 0;
        for (FormTabModel tab : formSchemeModel.getData()) {
            for (FormCompontModel compont : tab.getComponts()) {

                if (StringUtils.isNotEmpty(compont.getTable()) && !tableMap.containsKey(compont.getTable())) {
                    tableMap.put(compont.getTable(), String.valueOf(_index));
                    _index++;
                }

                if (compont.getType().equals("girdtable")) {
                    if (!girdTable.containsKey(compont.getTable())) {
                        girdTable.put(compont.getTable(), "1");
                    }
                } else if (StringUtils.isNotEmpty(compont.getField())) {
                    compontMap.put(compont.getId(), compont);
                    fieldSql += compont.getTable() + "tt." + compont.getField() + " as " + compont.getField() + tableMap.get(compont.getTable()) + ",";
                }
            }
        }
        // 确定主表
        List<FormTableModel> cTableList = new ArrayList<>();// 从表
        for (FormTableModel table : formSchemeModel.getDbTable()) {
            if (StringUtils.isEmpty(table.getRelationName())) {
                formSchemeModel.setMainTableName(table.getName());
                formSchemeModel.setMainTablePkey(table.getField());
            } else if (!girdTable.containsKey(table.getName())) {
                cTableList.add(table);
            }
        }
        fieldSql = fieldSql.substring(0, fieldSql.length() - 1);
        querySql += " SELECT " + fieldSql + " FROM  " + formSchemeModel.getMainTableName() + " " + formSchemeModel.getMainTableName() + "tt ";

        for (FormTableModel ctable : cTableList) {
            querySql += " LEFT JOIN  " + ctable.getName() + " " + ctable.getName() + "tt " + "  ON " + ctable.getName() + "tt." + ctable.getField() + " = " + ctable.getRelationName() + "tt." + ctable.getRelationField() + " ";
        }
        querySql += "  where 1=1 ";

        Map<String, Object> queryParamTemp = new HashMap<>();
        if (queryParam != null && queryParam.get("lrdateField") != null) {
            queryParamTemp.put("lrbegin", queryParam.get("lrbegin"));
            queryParamTemp.put("lrend", queryParam.get("lrend"));
            querySql += " AND (" + formSchemeModel.getMainTableName() + "tt." + queryParam.get("lrdateField").toString() + " >=@lrbegin AND " + formSchemeModel.getMainTableName() + "tt." + queryParam.get("lrdateField").toString() + " <=@lrend ) ";
        } else if (queryParam != null) // 复合条件查询
        {
            for (Map.Entry<String, Object> item : queryParam.entrySet()) {
                if (StringUtils.isNotEmpty(item.getValue().toString())) {
                    if (compontMap.get(item.getKey()).getType().equals("radio") || compontMap.get(item.getKey()).getType().equals("select") || compontMap.get(item.getKey()).getType().equals("datetimerange") || compontMap.get(item.getKey()).getType().equals("organize")) {
                        queryParamTemp.put(getFieldAlias(compontMap, tableMap, item.getKey()), item.getValue());
                        querySql += " AND " + compontMap.get(item.getKey()).getTable() + "tt." + compontMap.get(item.getKey()).getField() + " = @" + getFieldAlias(compontMap, tableMap, item.getKey());
                    } else if (compontMap.get(item.getKey()).getType().equals("checkbox")) {
                        querySql += " AND " + compontMap.get(item.getKey()).getTable() + "tt." + compontMap.get(item.getKey()).getField() + " in ('" + item.getValue().toString().replace(",", "','") + "')";
                    } else {
                        queryParamTemp.put(getFieldAlias(compontMap, tableMap, item.getKey()), "%" + item.getValue() + "%");
                        querySql += " AND " + compontMap.get(item.getKey()).getTable() + "tt." + compontMap.get(item.getKey()).getField() + " like @" + getFieldAlias(compontMap, tableMap, item.getKey());
                    }
                }
            }
        }
        queryParam.clear();
        for (Map.Entry<String, Object> item : queryParamTemp.entrySet()) {
            queryParam.put(item.getKey(), item.getValue());
        }
        return querySql;
    }


    /**
     * 获取字段别名
     *
     * @param compontMap 组件映射表
     * @param tableMap   表的名别映射表
     * @param id         主键id
     * @return
     */
    private String getFieldAlias(Map<String, FormCompontModel> compontMap, Map<String, String> tableMap, String id) {
        FormCompontModel compont = compontMap.get(id);
        String res = compont.getField() + tableMap.get(compont.getTable());
        return res;
    }

    /**
     * 获取自定义表单实例表的实体数据
     *
     * @param tableTree     主从表关系树
     * @param tableComponts 表与组件之间的关系
     * @param dbId          数据库主键
     * @param keyValue      主键值
     * @param pData         父表的数据值
     * @param res           结果数据
     */
    private void getInstanceTableData(List<TreeExtVo<FormTableModel>> tableTree, Map<String, List<FormCompontModel>> tableComponts, String dbId, String keyValue, Map<String, String> pData, Map<String, List<Map<String, Object>>> res) {
        for (TreeExtVo<FormTableModel> tableItem : tableTree) {
            String querySql = " SELECT ";
            if (tableComponts.containsKey(tableItem.getData().getName()) && !res.containsKey(tableItem.getData().getName())) {
                for (FormCompontModel compont : tableComponts.get(tableItem.getData().getName())) {
                    querySql += compont.getField() + " , ";
                }

                if (StringUtils.isEmpty(keyValue)) {
                    keyValue = pData.get(tableItem.getData().getRelationField());
                }
                querySql = querySql.substring(0, querySql.length() - 2);
                querySql += " FROM " + tableItem.getData().getName() + " WHERE " + tableItem.getData().getField() + " = #{keyValue}";

                Map<String, Object> params = new HashMap<>();
                params.put("keyValue", keyValue);

                List<Map<String, Object>> tableRows = tableService.findData(dbId, querySql, params);
                res.put(tableItem.getData().getName(), tableRows);

                // 获取它的从表数据
                if (tableItem.getChildNodes().size() > 0 && tableRows.size() > 0) {
                    Map<String, String> pDatatmp = new HashMap<>();
                    for (FormCompontModel compont : tableComponts.get(tableItem.getData().getName())) {
                        if (!pDatatmp.containsKey(compont.getField())) {
                            Object obj = tableRows.get(0).get(compont.getField());
                            pDatatmp.put(compont.getField(), obj == null ? null : obj.toString());
                        }
                    }
                    getInstanceTableData(tableItem.getChildNodes(), tableComponts, dbId, keyValue, pDatatmp, res);
                }

            }
        }
    }


    /**
     * 删除自定义表单实例表的实体数据
     *
     * @param tableTree   主从表关系树
     * @param tableMap    表与组件之间的关系
     * @param dbKey       数据库主键
     * @param keyValue    主键值
     * @param formDataMap 父表的数据值
     */
    private void deleteInstanceTable(List<TreeExtVo<FormTableModel>> tableTree, Map<String, List<FormCompontModel>> tableMap, String dbKey, String keyValue, List<Map<String, Object>> formDataMap) {
        for (TreeExtVo<FormTableModel> tableItem : tableTree) {
            String querySql = "";
            if (tableMap.containsKey(tableItem.getData().getName())) {
                if (StringUtils.isEmpty(keyValue)) {
                    keyValue = formDataMap.get(0).get(tableItem.getData().getRelationField()).toString();
                }

                // 如果有子表需要先获取数据
                if (tableItem.getChildNodes() != null && tableItem.getChildNodes().size() > 0) {
                    querySql = " SELECT * FROM " + tableItem.getData().getName() + " WHERE " + tableItem.getData().getField() + " = #{keyValue}";

                    Map<String, Object> params = new HashMap<>();
                    params.put("keyValue", keyValue);

                    List<Map<String, Object>> dt = tableService.findData(dbKey, querySql, params);
                    deleteInstanceTable(tableItem.getChildNodes(), tableMap, dbKey, keyValue, dt);
                }

                List<FieldValueParam> fieldValueParamlist = new ArrayList<>();
                FieldValueParam fieldValueParam = new FieldValueParam();
                fieldValueParam.setName("keyValue");
                fieldValueParam.setValue(keyValue);
                // 删除数据
                querySql = " DELETE FROM " + tableItem.getData().getName() + " WHERE " + tableItem.getData().getField() + " = #{keyValue}";

                Map<String, Object> params = new HashMap<>();
                for (FieldValueParam item : fieldValueParamlist) {
                    params.put(item.getName(), item.getValue());
                }
                tableService.excuteSqlWithParams(dbKey, querySql, params);
            }
        }

    }


    /**
     * 新增数据sql语句
     *
     * @param dbKey       数据库关键字
     * @param tableName   表名
     * @param tableMap    表名->组件映射
     * @param tablePkey   主键名
     * @param formDataMap 表单数据
     */
    private void insertSql(String dbKey, String tableName, String tablePkey, String processId, Map<String, List<FormCompontModel>> tableMap, Map<String, Object> formDataMap) {
        if (tableMap.containsKey(tableName) && tableMap.get(tableName).size() > 0) {
            List<FormDbTableFieldVo> list = tableService.findFieldsByTableName(dbKey, tableName);
            Map<String, String> dic = new HashMap<>();
            for (FormDbTableFieldVo item : list) {
                if (!dic.containsKey(item.getColumnName().toUpperCase())) {
                    dic.put(item.getColumnName().toUpperCase(), item.getColumnType());
                }
            }

            List<FieldValueParam> fieldValueParamlist = new ArrayList<>();
            String strSql = "INSERT INTO " + tableName + "(" + tablePkey + ", ";

            String sqlValue = " ('" + processId + "', ";
            for (FormCompontModel item : tableMap.get(tableName)) {
                FieldValueParam fieldValueParam = new FieldValueParam();
                if (StringUtils.isNotEmpty(item.getField()) && formDataMap.get(item.getId()) != null) {
                    strSql += item.getField() + ",";
                    sqlValue += " #{" + item.getField() + "},";

                    fieldValueParam.setName(item.getField());
                    if (dic.containsKey(item.getField().toUpperCase())) {
                        switch (dic.get(item.getField().toUpperCase())) {
                            case "DATE":
                                fieldValueParam.setType("DATE");
                                fieldValueParam.setValue(formDataMap.get(item.getId()));
                                break;
                            case "DATETIME":
                            case "DATETIME2":
                                fieldValueParam.setType("DATETIME");
                                fieldValueParam.setValue(formDataMap.get(item.getId()));
                                break;
                            case "NUMBER":
                            case "INT":
                            case "FLOAT":
                                fieldValueParam.setType("DECIMAL");
                                fieldValueParam.setValue(formDataMap.get(item.getId()));
                                break;
                            default:
                                fieldValueParam.setType("STRING");
                                fieldValueParam.setValue(formDataMap.get(item.getId()));
                                break;

                        }
                    }
                    fieldValueParamlist.add(fieldValueParam);
                } else if (item.getType().equals("girdguid")) {
                    strSql += item.getField() + ",";
                    sqlValue += " #{" + item.getField() + "},";
                    fieldValueParam.setName(item.getField());
                    fieldValueParam.setValue(UUIDUtils.getOriginalUUIDWithoutBar());
                    fieldValueParam.setType("STRING");
                    fieldValueParamlist.add(fieldValueParam);
                }
            }
            strSql = strSql.substring(0, strSql.length() - 1);
            sqlValue = sqlValue.substring(0, sqlValue.length() - 1);

            strSql += " ) VALUES " + sqlValue + ")";

            Map<String, Object> params = new HashMap<>();
            for (FieldValueParam item : fieldValueParamlist) {
                params.put(item.getName(), item.getValue());
            }
            tableService.excuteSqlWithParams(dbKey, strSql, params);
        }
    }


    /**
     * 更新数据sql语句
     *
     * @param dbKey       数据库关键字
     * @param tableName   表名
     * @param pkey        主键字段
     * @param pkeyValue   主键数据
     * @param tableMap    表名->组件映射
     * @param formDataMap 上传的数据
     */
    private void updateSql(String dbKey, String tableName, String pkey, String pkeyValue, Map<String, List<FormCompontModel>> tableMap, Map<String, Object> formDataMap) {
        if (tableMap.containsKey(tableName) && tableMap.get(tableName).size() > 0) {
            List<FormDbTableFieldVo> list = tableService.findFieldsByTableName(dbKey, tableName);
            Map<String, String> dic = new HashMap<>();
            for (FormDbTableFieldVo item : list) {
                if (!dic.containsKey(item.getColumnName().toUpperCase())) {
                    dic.put(item.getColumnName().toUpperCase(), item.getColumnType());
                }
            }

            List<FieldValueParam> fieldValueParamlist = new ArrayList<>();
            String strSql = " UPDATE   " + tableName + " SET  ";
            for (FormCompontModel item : tableMap.get(tableName)) {
                if (StringUtils.isNotEmpty(item.getField()) && !item.getField().equals(pkey) && formDataMap.get(item.getId()) != null) {
                    strSql += item.getField() + "=#{" + item.getField() + "},";
                    FieldValueParam fieldValueParam = new FieldValueParam();
                    fieldValueParam.setName(item.getField());
                    if (dic.containsKey(item.getField().toUpperCase())) {
                        switch (dic.get(item.getField().toUpperCase())) {
                            case "DATE":
                                fieldValueParam.setType("DATE");
                                fieldValueParam.setValue(formDataMap.get(item.getId()));
                                break;
                            case "DATETIME":
                            case "DATETIME2":
                                fieldValueParam.setType("DATETIME");
                                fieldValueParam.setValue(formDataMap.get(item.getId()));
                                break;
                            case "NUMBER":
                            case "INT":
                            case "FLOAT":
                                fieldValueParam.setType("DECIMAL");
                                fieldValueParam.setValue(formDataMap.get(item.getId()));
                                break;
                            default:
                                fieldValueParam.setType("STRING");
                                fieldValueParam.setValue(formDataMap.get(item.getId()));
                                break;
                        }
                    }
                    fieldValueParamlist.add(fieldValueParam);
                } else if (!item.getField().equals(pkey) && formDataMap.get(item.getId()) != null) {
                    strSql += item.getField() + "= null,";
                }
            }
            strSql = strSql.substring(0, strSql.length() - 1);
            strSql += " WHERE " + pkey + "='" + pkeyValue + "'";

            Map<String, Object> params = new HashMap<>();
            for (FieldValueParam item : fieldValueParamlist) {
                params.put(item.getName(), item.getValue());
            }
            tableService.excuteSqlWithParams(dbKey, strSql, params);
        }
    }

}
